/**
 * 
 */
package com.juno.cafenoa.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


/**
 * asyncTask 통신하는 class<br>
 * 기타 사용법은 LoginActivity에 정의된 AsyncTaskCompleteListener 참조
 * @author JUNHO
 */
public class HttpPostTask extends AsyncTask<String, Void , Boolean > {
	private Context mContext;
	private List<NameValuePair> valuePairs;
	private final String apiUrl;
	private String responseString ;
	
	private AsyncTaskCompleteListener listener;
	
	private static final int HTTP_CONNECT_TIMEOUT = 1000 * 5;
	private static final int HTTP_RESPONSE_TIMEOUT = 1000 * 8; 
	
	private static class InflatingEntity extends HttpEntityWrapper {

        public InputStream getContent() throws IOException {
            return new GZIPInputStream(wrappedEntity.getContent());
        }

        public long getContentLength() {
            return -1L;
        }

        public InflatingEntity(HttpEntity wrapped) {
            super(wrapped);
        }
    }
	
	public HttpPostTask( Context context , List<NameValuePair> valuePairs , String apiUrl , AsyncTaskCompleteListener listener ){
		this.mContext = context;
		this.valuePairs = valuePairs;
		this.apiUrl = apiUrl;
		this.listener = listener;
	}
	
	@Override
	protected Boolean doInBackground(String... params) {
		// TODO Auto-generated method stub
		try{
			HttpPost httpPost = new HttpPost( apiUrl );
	        httpPost.setEntity(new UrlEncodedFormEntity(valuePairs,"UTF-8"));
//	        httpPost.addHeader("Content-Type","text/html");
	        BasicHttpParams httpParameters = new BasicHttpParams();
	        int timeoutConnection = HTTP_CONNECT_TIMEOUT;
	        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
	        int timeoutSocket = HTTP_RESPONSE_TIMEOUT;
	        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
	        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
	        httpClient.addRequestInterceptor( new HttpRequestInterceptor(){

				@Override
				public void process(HttpRequest request, HttpContext context)
						throws HttpException, IOException {
					 if(!request.containsHeader("Accept-Encoding"))
						 request.addHeader("Accept-Encoding", "gzip");
				}
	        	
	        });
	        
	        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
				
					@Override
					public void process(HttpResponse response, HttpContext context)
							throws HttpException, IOException {
						HttpEntity entity = response.getEntity();
		                Header encoding = entity.getContentEncoding();
		                if(encoding != null)
		                {
		                    HeaderElement arr[] = encoding.getElements();
		                    int len = arr.length;
		                    int i = 0;
		                    do
		                    {
		                        if(i >= len)
		                            break;
		                        HeaderElement element = arr[i];
		                        if(element.getName().equalsIgnoreCase("gzip"))
		                        {
		                            response.setEntity(new InflatingEntity(response.getEntity()));
		                            break;
		                        }
		                        i++;
		                    } while(true);
		                }
					}
				}
			);
	        		
	        
	        BasicHttpResponse httpResponse = (BasicHttpResponse)httpClient.execute(httpPost);
//	        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "EUC-KR"));
	        responseString = EntityUtils.toString(httpResponse.getEntity());
	        
	        if( responseString != null && !"".equals( responseString ) )
	        	return true;
	        
		}
		catch( SocketTimeoutException ste ){
			
		}
		catch( MalformedURLException mue ){
			
		}
		catch( IOException e ){
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	protected void onPostExecute( Boolean result ){
		listener.onTaskComplete( responseString , result );
	}

}
